﻿using AutoMapper;
using MediatR;
using Traceability.App.Api.Application.Command.Add;
using Traceability.App.Domain;
using Traceability.App.ErrorCode;
using Traceability.App.Instructure;

namespace Traceability.App.Api.Application.Handler.Add
{
    public class AddTuCompanyHandler : IRequestHandler<AddTuCompanyCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<SlaughterCompany> slaughterRepo;
        private readonly IMapper mapper;

        public AddTuCompanyHandler(IBaseRepository<SlaughterCompany> slaughterRepo,IMapper mapper) 
        {
            this.slaughterRepo = slaughterRepo;
            this.mapper = mapper;
        }
        public Task<ApiResult<int>> Handle(AddTuCompanyCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();
            var slaughterCompany = slaughterRepo.GetAll().Where(x => x.Batch == request.Batch).FirstOrDefault();
            if (slaughterCompany==null)
            {
                var entity = mapper.Map<SlaughterCompany>(request);
                slaughterRepo.Add(entity);
            }
            else
            {
                slaughterCompany.CompanyName = request.CompanyName;
                slaughterCompany.Province = request.Province;
                slaughterCompany.City = request.City;
                slaughterCompany.County = request.County;
                slaughterCompany.SteupDateTime = request.SteupDateTime;
                slaughterCompany.CompanyProfile = request.CompanyProfile;
                slaughterRepo.Update(slaughterCompany);
            }
            res.Msg = "设置屠宰企业信息成功";
            res.Code = ApiEnum.Success;
            return Task.FromResult(res);
        }
    }
}
